﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EarthGrid.log
{
    public class Log
    {
        private static String Path = Directory.GetCurrentDirectory() + "\\logs";

        private static StreamWriter GetWriter()
        {
            String path = Path;
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            path = path + "\\" + DateTime.Now.ToString("yyyyMM");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            path = path + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
            return new StreamWriter(path, true, System.Text.Encoding.UTF8);
        }

        public delegate void MessageToTextBox(String msg);

        private static MessageToTextBox message;

        public static void setDelegate(MessageToTextBox messageToTextBox)
        {
            message = messageToTextBox;
        }

        public static async Task InfoAsync(String str)
        {
            using (StreamWriter writer = GetWriter())
            {
                string time = DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss");
                if (null != message) message(time + " - [info] - " + str);
                writer.WriteLineAsync(time + " - [info] - " + str);
            }
        }

        public static async Task ErrorAsync(String str)
        {
            using (StreamWriter writer = GetWriter())
            {
                string time = DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss");
                if (null != message) message(time + " - [error] - " + str);
                writer.WriteLineAsync(time + " - [error] - " + str);
            }
        }

        public static async Task InfoAsync(String str, Object[] values)
        {
            if (null == values || values.Length == 0)
                InfoAsync(str);
            try
            {
                InfoAsync(String.Format(str, values));
            }
            catch (Exception e)
            {
                ErrorAsync(e.Message);
            }
        }

        public static async Task ErrorAsync(String str, Object[] values)
        {
            if (null == values || values.Length == 0)
                ErrorAsync(str);
            try
            {
                ErrorAsync(String.Format(str, values));
            }
            catch (Exception e)
            {
                ErrorAsync(e.Message);
            }
        }
    }
}
